import axios from 'axios'
import qs from 'Qs'
import $globalData from '@/tools/globalData.js'

export default {
  install: function (Vue) {
    Vue.prototype.request = (param) => request(param)
  },
  request
}

/*
传入格式x
{
  url:string,//地址
  method:string//请求方式 默认'GET',
  data:object//必要参数
}
*/

function request (object) {
  // 初始化
  let method = object.method !== undefined ? object.method : 'GET'
  // console.log(qs.stringify(object.data))
  let data_ = object.data !== undefined ? object.data : {}
  if ($globalData.token !== '') { data_.token = $globalData.token }
  let data = qs.stringify(object.data)
  if (method === 'GET') { return get(object, data) }

  // console.log('进行axios的值', object)
  return new Promise((resolve, reject) => {
    axios({
      headers: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: method,
      url: object.url,
      data: data
    }).then(
      res => {
        resolve(res)
      },
      res => {
        console.log('请求错误')
        reject(res)
      }
    )
  })
}

function get (object, data) {
  // console.log('data', data)
  let url = object.url + '?' + data
  return new Promise((resolve, reject) => {
    axios({
      method: 'GET',
      url: url
    }).then(
      res => {
        resolve(res)
      },
      res => {
        console.log('请求错误')
        reject(res)
      }
    )
  })
}
